package code.cando;

import java.util.Arrays;

/**
 * author : yeswater
 * date : 2023/12/4
 * <p>
 * 寻找正序数组的中位数
 */

public class T004 {
    public static void main(String[] args) {
        int[] nums1 = {1, 3};
        int[] nums2 = {2};
        System.out.println(findMedianSortedArrays(nums1, nums2));
    }

    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int len1 = nums1.length;
        int len2 = nums2.length;
        if (len1 == 0 && len2 == 0) {
            return 0;
        }
        if (len1 == 0 && len2 == 1) {
            return nums2[0];
        }
        if (len2 == 0 && len1 == 1) {
            return nums1[0];
        }
        int len3 = len1 + len2;
        int[] nums3 = new int[len3];
        // 编译器优化
        System.arraycopy(nums1, 0, nums3, 0, len1);
        System.arraycopy(nums2, 0, nums3, len1, len2);
        Arrays.sort(nums3);
        int index = len3 / 2;
        int rest = len3 % 2;
        if (rest == 0) {
            return (double)(nums3[index] + nums3[index - 1]) / 2;
        }
        return nums3[index];
    }
}
